from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_LINE_SPACING


class DocxGenerator:
    def __init__(self):
        self.font_name = "宋体"
        self.font_size = 9
        self.line_spacing = 1
    
    def generate(self, code_lines, output_path, progress_callback=None):
        doc = Document()
        style = doc.styles['Normal']
        font = style.font
        font.name = self.font_name
        font.size = Pt(self.font_size)
        
        # 添加标题
        title = doc.add_paragraph("软件著作权代码文档")
        title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        title.runs[0].font.size = Pt(16)
        title.runs[0].font.bold = True
        
        doc.add_paragraph("\n")
        
        # 添加代码内容
        total = len(code_lines)
        for i, line in enumerate(code_lines):
            p = doc.add_paragraph(line)
            p.paragraph_format.line_spacing = self.line_spacing
            # 设置段落格式
            # p.paragraph_format.line_spacing_rule = WD_LINE_SPACING.SINGLE  # 单倍行距
            p.paragraph_format.space_before = Pt(0)  # 段前0磅
            p.paragraph_format.space_after = Pt(0)  # 段后0磅
            
            if progress_callback and i % 50 == 0:
                progress = int((i / total) * 100)
                progress_callback(progress)
        
        doc.save(output_path)
